/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import BD.CriaConexao;
import IRepositorios.IRepositorioCliente;
import Relatorios.RelatorioMet;
import control.Locadora;
import control.dao.metodosClientes;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import model.Cliente;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

/**
 *
 * @author Andre
 */
public class FormRelatorios extends javax.swing.JFrame {
    static File arquivo;
    private IRepositorioCliente IRCliente;
    DefaultTableModel tmCliente = new DefaultTableModel(null, new String[]{"Nome"});
    private List<Cliente> listCliente;
    ListSelectionModel lsmCliente;
    private Locadora loc;
    /**
     * Creates new form FormRelatorios
     */
    public FormRelatorios() {
        initComponents();
        BufferedImage image=null;
        File imageFile=new File(".\\src\\Imagens\\logo.png");
        try {
            image=ImageIO.read(imageFile);
            
        } catch (IOException ex) {
        }
        this.setIconImage(image);
        IRCliente= new metodosClientes();
        
        
        loc= new Locadora(null, IRCliente, null, null,null);
        DesabilitaDados();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jDialog1 = new javax.swing.JDialog();
        jFileChooser1 = new javax.swing.JFileChooser();
        jDialog2 = new javax.swing.JDialog();
        jFileChooser2 = new javax.swing.JFileChooser();
        jSeparator1 = new javax.swing.JSeparator();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jTF_pesquisarCliente = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTabela_Cliente = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        jFileChooser1.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFileChooser1ActionPerformed(evt);
            }
        });
        jDialog1.getContentPane().add(jFileChooser1, java.awt.BorderLayout.CENTER);

        jFileChooser2.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        jFileChooser2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFileChooser2ActionPerformed(evt);
            }
        });
        jDialog2.getContentPane().add(jFileChooser2, java.awt.BorderLayout.CENTER);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Relatórios");
        getContentPane().setLayout(null);
        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(10, 60, 350, 20);

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("Relatório de histórico de locações");
        jRadioButton1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton1ItemStateChanged(evt);
            }
        });
        getContentPane().add(jRadioButton1);
        jRadioButton1.setBounds(20, 20, 190, 23);

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setText("Top Filmes");
        jRadioButton2.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton2ItemStateChanged(evt);
            }
        });
        getContentPane().add(jRadioButton2);
        jRadioButton2.setBounds(260, 20, 93, 23);

        jTF_pesquisarCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTF_pesquisarClienteMouseClicked(evt);
            }
        });
        jTF_pesquisarCliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTF_pesquisarClienteKeyReleased(evt);
            }
        });
        getContentPane().add(jTF_pesquisarCliente);
        jTF_pesquisarCliente.setBounds(130, 120, 160, 20);

        jLabel17.setText("Pesquisar:");
        getContentPane().add(jLabel17);
        jLabel17.setBounds(70, 120, 60, 20);

        jTabela_Cliente.setModel(tmCliente);
        jTabela_Cliente.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmCliente = jTabela_Cliente.getSelectionModel();
        lsmCliente.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
                if(! e.getValueIsAdjusting()){
                    JTTabelaLinhaSelecionadaCliente(jTabela_Cliente);
                }
            }
        }
    );
    jScrollPane3.setViewportView(jTabela_Cliente);

    getContentPane().add(jScrollPane3);
    jScrollPane3.setBounds(70, 150, 220, 120);

    jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel4.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Selecione um Cliente", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
    getContentPane().add(jLabel4);
    jLabel4.setBounds(50, 90, 260, 200);

    jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jButton1.setText("Gerar Relatório");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton1);
    jButton1.setBounds(100, 310, 160, 40);

    jLabel1.setText("Entre com a quantidade de filmes para serem apresentados");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(40, 90, 300, 14);

    jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(150, 140, 70, 20);

    jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jButton2.setText("Gerar");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton2);
    jButton2.setBounds(130, 200, 110, 40);

    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-394)/2, (screenSize.height-426)/2, 394, 426);
    }// </editor-fold>//GEN-END:initComponents

    private void jTF_pesquisarClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTF_pesquisarClienteMouseClicked
        jTabela_Cliente.clearSelection();        // TODO add your handling code here:
    }//GEN-LAST:event_jTF_pesquisarClienteMouseClicked

    private void jTF_pesquisarClienteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTF_pesquisarClienteKeyReleased
        listCliente = loc.buscarClienteList(jTF_pesquisarCliente.getText() + "%");
        mostraPesquisaCliente(listCliente);
    }//GEN-LAST:event_jTF_pesquisarClienteKeyReleased

    private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton1ItemStateChanged
        DesabilitaDados();
        jTF_pesquisarClienteKeyReleased(null);
        jTF_pesquisarClienteKeyReleased(null);
        
       jTF_pesquisarCliente.setVisible(true);
       jTabela_Cliente.setVisible(true);
       jButton1.setVisible(true);
       jScrollPane3.setVisible(true);
       jLabel17.setVisible(true);
       jLabel4.setVisible(true);
               
    }//GEN-LAST:event_jRadioButton1ItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(jRadioButton1.isSelected()){
            if(jTabela_Cliente.getSelectedRow() > -1){
           java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        jDialog1.setBounds((screenSize.width-625)/2, (screenSize.height-430)/2, 625, 430);
        jDialog1.setVisible(true);
            }
       }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser1ActionPerformed

        arquivo = jFileChooser1.getSelectedFile();


        jDialog1.setVisible(false);
        if (arquivo != null) {
            String adober;

            adober = String.valueOf(arquivo);
            File pasta = new File(adober + "/Relatorios");
            pasta.mkdir();
            adober = adober + "/Relatorios";
            System.out.println(adober);
            if (!adober.equals("null")) {
                try {
                    Connection con = CriaConexao.getConexao();

                    HashMap parametros = new HashMap();

                    CriaConexao Con = new CriaConexao();
                    RelatorioMet obm = new RelatorioMet();

                    File f = new File(adober + "/Histórico");
                    f.delete();
                    File dir2 = new File(adober + "/Histórico");
                    dir2.mkdir();
                    String adober2;
                    adober2 = String.valueOf(dir2);
                    


                    parametros = (HashMap) obm.Met(listCliente.get(jTabela_Cliente.getSelectedRow()).getCpf());
                    
                    JasperPrint jp = null;
                    try {
                        jp = JasperFillManager.fillReport("./src/Relatorios/historico_locacoes.jasper", parametros, con);
                    } catch (JRException ex) {
                        Logger.getLogger(FormRelatorios.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        JasperExportManager.exportReportToPdfFile(jp, adober2 + "/" + "Histórico  " + listCliente.get(jTabela_Cliente.getSelectedRow()).getNome() + ".pdf");
                    } catch (JRException ex) {
                        Logger.getLogger(FormRelatorios.class.getName()).log(Level.SEVERE, null, ex);
                    }



                } catch (SQLException ex) {
                    Logger.getLogger(FormRelatorios.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            JOptionPane.showMessageDialog(rootPane, "Relatório gerado com sucesso");
        }
    }//GEN-LAST:event_jFileChooser1ActionPerformed

    private void jRadioButton2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton2ItemStateChanged
        DesabilitaDados(); 
        if(jRadioButton2.isSelected()){
            jLabel1.setVisible(true);
            jTextField1.setVisible(true);
            jButton2.setVisible(true);
                    
        }
    }//GEN-LAST:event_jRadioButton2ItemStateChanged

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if(!"".equals(jTextField1.getText())){
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        jDialog2.setBounds((screenSize.width-625)/2, (screenSize.height-430)/2, 625, 430);
        jDialog2.setVisible(true);    
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jFileChooser2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser2ActionPerformed
        arquivo = jFileChooser2.getSelectedFile();


        jDialog2.setVisible(false);
        if (arquivo != null) {
            String adober;

            adober = String.valueOf(arquivo);
            File pasta = new File(adober + "/Relatorios");
            pasta.mkdir();
            adober = adober + "/Relatorios";
            System.out.println(adober);
            if (!adober.equals("null")) {
                try {
                    Connection con = CriaConexao.getConexao();

                    HashMap parametros = new HashMap();

                    CriaConexao Con = new CriaConexao();
                    RelatorioMet obm = new RelatorioMet();

                    File f = new File(adober + "/TOP Filmes");
                    f.delete();
                    File dir2 = new File(adober + "/TOP Filmes");
                    dir2.mkdir();
                    String adober2;
                    adober2 = String.valueOf(dir2);
                    


                    parametros = (HashMap) obm.Met2();
                    
                    JasperPrint jp = null;
                    try {
                        jp = JasperFillManager.fillReport("./src/Relatorios/TOP.jasper", parametros, con);
                    } catch (JRException ex) {
                        Logger.getLogger(FormRelatorios.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        JasperExportManager.exportReportToPdfFile(jp, adober2 + "/" + "TOP Filmes(tamanho " + jTextField1.getText() + ").pdf");
                    } catch (JRException ex) {
                        Logger.getLogger(FormRelatorios.class.getName()).log(Level.SEVERE, null, ex);
                    }



                } catch (SQLException ex) {
                    Logger.getLogger(FormRelatorios.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            JOptionPane.showMessageDialog(rootPane, "Relatório gerado com sucesso");
        }
    }//GEN-LAST:event_jFileChooser2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FormRelatorios().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JDialog jDialog2;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFileChooser jFileChooser2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTF_pesquisarCliente;
    private javax.swing.JTable jTabela_Cliente;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    private void DesabilitaDados() {
        jTF_pesquisarCliente.setVisible(false);
       jTabela_Cliente.setVisible(false);
       jButton1.setVisible(false);
       jScrollPane3.setVisible(false);
       jLabel17.setVisible(false);
       jLabel4.setVisible(false);
       jLabel1.setVisible(false);
            jTextField1.setVisible(false);
            jButton2.setVisible(false);
    }

    private void mostraPesquisaCliente(List<Cliente> listCliente) {
         while (tmCliente.getRowCount() > 0) {
           tmCliente.removeRow(0);
        }
        if (!listCliente.isEmpty()) {
             String[] linha = new String[]{null};
            for (int i = 0; i < listCliente.size(); i++) {
                tmCliente.addRow(linha);
                tmCliente.setValueAt(listCliente.get(i).getNome(), i, 0);
        } 
        }
    }
    
    private void JTTabelaLinhaSelecionadaCliente(JTable tabela) {
        
    }
    
}
